package com.kusiri.kframework.window.uicontainer
{
	import com.kusiri.kframework.IKfApplication;
	import com.kusiri.kframework.KfApplicationLocator;
	import com.kusiri.kframework.ui.IKfUiComponent;
	import com.kusiri.kframework.ui.IKfUiComponentOptions;
	import com.kusiri.kframework.ui.IKfUiContainer;
	import com.kusiri.window.Window;
	import com.kusiri.window.WindowManager;
	
	import mx.core.IContainer;
	import mx.core.IFlexDisplayObject;

	/**
	 * displayConfiguration must contain title
	 */
	public class KfWindowUiContainer implements IKfUiContainer
	{
		private var windowManager : WindowManager;
		private var kfApplication : IKfApplication = new KfApplicationLocator().kfApplication; 

		/**
		 * Gets a blank ui component options object
		 */
		public function getBlankComponentOptions() : IKfUiComponentOptions
		{
			return new KfWindowedComponentOptions();
		}
		
		/**
		 * 
		 */
		public function removeUiComponent(kfUiComponent : IKfUiComponent) : void
		{
			removeUiComponentContaining(kfUiComponent.__uiComponent);
		}
		
		/**
		 * 
		 */
		public function removeUiComponentContaining(uiComponent : IFlexDisplayObject) : void
		{
			var w:Window = windowManager.getContainingWindow(uiComponent);
			if (w)
			{
				// deactivate - remove listeners etc.
				w.remove();
			}
		}
		

		/**
		 * Add a UI component to the display.
		 * Configuration for display of component is in KfUiComponent.displayConfiguration
		 */
		public function addUiComponent(kfUiComponent : IKfUiComponent, onSuccess : Function = null, onFail : Function = null, config : IKfUiComponentOptions = null) : void
		{			
			var configuration : KfWindowedComponentOptions = config as KfWindowedComponentOptions;
			
			kfApplication.waitingForSomething();
			
			kfApplication.context.initializeComponent(kfUiComponent,
				function(kfUiComponent:IKfUiComponent) : void
				{
			
					kfApplication.finishedWaitingForSomething();
			
					if (!configuration)
					{
						windowManager.newWindow(kfUiComponent, '', kfUiComponent.__uiComponent);
						return;
					}
						
					windowManager.newWindow(kfUiComponent, configuration.title, kfUiComponent.__uiComponent, configuration.width, configuration.height, configuration.x, configuration.y);
					
					if (onSuccess != null) onSuccess(kfUiComponent);
				},
				function (e:*) : void
				{
					kfApplication.finishedWaitingForSomething();
					onFail(e);
				}
				
			);
		}
		
		/**
		 * Set what the UI container is to be underneath
		 */
		public function initialize(parent : IContainer, callback : Function ) : void
		{
			windowManager = new WindowManager();
			windowManager.init(parent, callback);
		}
		
		/**
		 * Whether the UI is enabled or not
		 */
		public function set enabled(value:Boolean) : void
		{
			windowManager.container.enabled = value;
		}
		
	}
}